$(function () {
    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
            bghtmxGrid($.webPath() + '/htgl/bghtgl/bghtgl_htmx?bghtId=' + $("[name='bght.id']").val() || '', cddata, data);
        })
    });

    if ($("[name='bght.lj.id']").val()) {
        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': $("[name='bght.lj.id']").val()}, function (data) {
            var sydata = [], xydata = [];
            $(data).each(function (i, item) {
                if (item.lx == 'sy') {
                    sydata.push(item);
                }
                else if (item.lx == 'xy') {    //下游
                    xydata.push(item);
                }
            })
            $("#bght_hzf_id").loadLocalRegion(sydata, '');
        });
    }

    //路径选择
    if ($("#bght_lj_id").length > 0) {
        $("#bght_lj_id").ljcombobox($("#bght_zggsId").val(), '5', {
            onSelect: function (record) {
                //展示详细
                $("#bght_lj_id").next().find('.combo-text').ljDetail(record.id);
                 var sydata = [], xydata = [];
                 $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': record.id}, function (data) {
                     $(data).each(function (i, item) {
                         if (item.lx == 'sy') {   //上游
                             sydata.push(item);
                         } else if (item.lx == 'xy') {    //下游
                             xydata.push(item);
                         }
                     })

                     if ($("[name='bght.id']").val() == '') {
                         if (sydata && sydata[0])
                             $("#bght_hzf_id").loadLocalRegion(sydata, sydata[0].id);
                     } else {
                         if (sydata && sydata[0])
                             $("#bght_hzf_id").loadLocalRegion(sydata, '');
                     }

                 })
            },
            onChange: function (newValue) {
                var data = $("#bght_lj_id").combobox("getData");
                data = $.grep(data, function (v, i) {
                    return v.id == newValue;
                });
                if (data.length <= 0) {
                    $("#bght_lj_id").next().find('.combo-text').tooltip("destroy");
                }
            }
        });
    }
    
    //合作方加载
    $("#bght_hzf_id").combobox({valueField: 'id', textField: 'jc'});

    //付款方式
    //$("#bght_fkfs_id").sjzdcombobox('fkfs');
    $("[name='bght.fkfs.id']").sjzdcombobox('fkfs');

    //上传附件
    $("#bght-uploadify").upload('bght-fileQueue', {
        onUploadSuccess: function (file, data, response) {
            var obj = eval('(' + data + ')');
            $("#bght-fileQueue .data").remove();
            $("#bght-fileQueue .uploadify-progress").fadeOut(500, function () {
                $(this).remove();
            });
            $("#" + file.id).append("<input type='hidden' id='bght-file" + obj.fileId + "' name='bght.fjList.id' value='" + obj.fileId + "'/>");
            $("#" + file.id + " .cancel a").bind('click', function () {
                $(this).attr('href', 'javascript:void(0)');
                deleteBghtFile(obj.fileId, file.id);
            });
        }
    });

    //新增物资计划明细
    $("#bghtgl_bghtmx_toolbar [name='xzbghtmx']").click(function () {
        searchcodewindow(bghtmx_searchWindowOKbtnHandler);
    });
    //删除物资计划明细
    $("#bghtgl_bghtmx_toolbar [name='scbghtmx']").click(function () {
        var rows = $("#bght_mx").edatagrid('getChecked');
        if (rows) {
            $.messager.confirm('提示', '是否确定删除合同明细?', function (r) {
                if (r) {
                    $.each(rows, function (i, val) {
                        var index = $("#bght_mx").edatagrid('getRowIndex', val);
                        $("#bght_mx").edatagrid('deleteRow', index);
                    });
                }
                countBghtSumCg();
            });
        }
        $("#bght_mx").edatagrid('resize');
    });

    // 加载合同模板
    var htdyId = $("[name='bghtdyid']").val() || 99;
    if ($("[name='bght.id']").val()) {
        $("[name='bght_htmb']").htmbcombobox(false, htdyId,{
            onChange: function (oldValue, newValue) {
                // 加载合同文本
                $.ajax({
                    type: "POST",
                    url: $.webPath() + "/htdygl/htwb/htwbDetail",
                    dataType: "html",
                    data: {htmbId: oldValue, htdyId: htdyId, htId: $("[name='bght.id']").val()},
                    beforeSend: function () {
                        $.messager.progress();
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        $('#htwb_bght_id').html(data);
                        if (data.statusCode == 300) {
                        }
                        if (data.statusCode == 200) {
                        }
                    }
                });
            }
        });
        // 如果已经有了文本加载文本
        $.ajax({
            type: "POST",
            url: $.webPath() + "/htdygl/htwb/htwbDetail",
            dataType: "html",
            data: {htdyId: htdyId, htId: $("[name='bght.id']").val()},
            beforeSend: function () {
                $.messager.progress();
            },
            success: function (data) {
                $.messager.progress("close");
                $('#htwb_bght_id').html(data);
            }
        });
    }
});

//保供合同明细
function bghtmxGrid(href, cdOptions, fsOptions) {
    $("#bght_mx").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        toolbar: "#bghtgl_bghtmx_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'wzgg.oldcode', title: '物资编码', width: 50},
                {field: 'wzgg.name', title: '物资名称', width: 40},
                {field: 'wzgg.ggxh', title: '规格型号', width: 40},
                {field: 'wzgg.dw', title: '单位', width: 20},
                {field: 'cd.id', editor: {type: 'combobox', options: {
                    data: cdOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '150'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < cdOptions.length; i++) {
                        if (cdOptions[i].id == value) return cdOptions[i].z;
                    }
                    return value;
                }, title: '产地', width: 40},
                {field: 'sbsl', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '数量',
                    formatter:function(value){
                        var sl = formatSl(value,",");
                        return sl;
                    } ,width: 65},
                {field: 'jzfs.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '55'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title: '记重方式', width: 40},
                {field: 'hsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '含税价(元)',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    } ,width: 70},
                {field: 'bhsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '不含税价(元)',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    },width: 70},
                {field: 'hsje', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '含税金额(元)',
                    formatter:function(value){
                        var sl = formatJe(value,",");
                        return sl;
                    },width: 80},
                {field: 'ph', title: '牌号', editor:{type:'text'}, width: 40},
                {field: 'jthsjsl', title: '交提货时间及数量', editor:{type:'text'}, width: 65}
            ]
        ],
        onSelect: function (rowIndex) {
            //获取每个单元格
            $("#bght_mx").edatagrid('editRow', rowIndex);
            var editors = $("#bght_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var bhsjEditor = editors[4];
            var hsjEditor = editors[3];
            var hsjeEditor = editors[5];
            var sbslEditor = editors[1];
            sbslEditor.target.unbind('blur').bind('blur', function () {
                $(sbslEditor.target).numberbox('setValue', $(sbslEditor.target).val());
                $(bhsjEditor.target).numberbox('setValue', formatMoneyFourWei(tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#bght_sl").combobox('getValue'))));
                $(hsjeEditor.target).numberbox('setValue', formatMoneyFourWei($(hsjEditor.target).numberbox('getValue') * $(sbslEditor.target).numberbox('getValue')))
                countBghtSum(rowIndex, $(sbslEditor.target).numberbox('getValue'), $(hsjEditor.target).numberbox('getValue'));
            });
            hsjEditor.target.unbind('blur').bind('blur', function () {
                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());
                $(bhsjEditor.target).numberbox('setValue', formatMoneyFourWei(tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#bght_sl").combobox('getValue'))));
                $(hsjeEditor.target).numberbox('setValue', formatMoneyFourWei($(hsjEditor.target).numberbox('getValue') * $(sbslEditor.target).numberbox('getValue')));
                countBghtSum(rowIndex, $(sbslEditor.target).numberbox('getValue'), $(hsjEditor.target).numberbox('getValue'));
            });
        }
    })
}

//查询物资代码确定按钮回调函数
function bghtmx_searchWindowOKbtnHandler(data) {
    var rowdatas = $.map(data, function (n, i) {
        return {
            'wzgg.id': n.id,
            'wzgg.oldcode': n.oldcode,
            'wzgg.name': n.name,
            'wzgg.ggxh': n.ggxh,
            'wzgg.dw': n.dw,
            'cd.id': null,
            'ck': '',
            'jzfs.id': null,
            'bz': '',
            'sbsl': 0
        };
    });
    $.each(rowdatas, function () {
        $("#bght_mx").edatagrid('appendRow', this);
    });
}

//计算计划总量
function countBghtSum(index, countSbsl, counthsj) {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#bght_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        if (i == index) {
            sbsl = parseFloat(countSbsl);
            hsj = parseFloat(counthsj);
        }
        sbsl = isNaN(sbsl) ? 0.00 : sbsl;
        hsj = isNaN(hsj) ? 0.00 : hsj;
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += hsj * sbsl;
    }
    addBghtFooter(sumsbsl, sumhsj, sumhsje);
}

//计算计划总量
function countBghtSumCg() {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#bght_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += hsj * sbsl;
    }
    addBghtFooter(sumsbsl, sumhsj, sumhsje);
}

function addBghtFooter(sumsbsl, sumhsj, sumhsje) {
    var sumbhsj = 0;
    if ($("#bght_sl")) {
        sumbhsj = tax.getNotIncludingTaxPrice(sumhsj, ($("#bght_sl").combobox('getValue')));
    }
    var footer = [
        {"wzgg.code": "合计", "sbsl": sumsbsl, "bhsj": sumbhsj, "hsj": sumhsj, "hsje": sumhsje}
    ];
    if (footer != null)
        $("#bght_mx").edatagrid('reloadFooter', footer);
}

function deleteBghtFile(fileId, id) {
    $.messager.confirm('确认', '是否确认删除此附件', function (r) {
        if (r) {
            $.post($.webPath() + '/base/fj/deleteFj', {'fjId': fileId}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $("#bght-file" + fileId).remove();
                    $("#" + id).fadeOut(500, function () {
                        $(this).remove();
                    });
                }
            });
        }
    })
}